import React from "react";
import * as ReactDOM from "react-dom";
import NavigatorViewConfig from "../NavigatorViewConfig";
import {INavigator, NavigatorAppStatesType} from "../NavigatorTypes";
import NavigatorStack from "../NavigatorStack";
import {Image, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import NavigatorConfig from "../NavigatorConfig";
import Logger from "../../../libs/sdk/echatim/log/Logger";
import UUID from "../../../libs/sdk/echatim/common/UUID";
import {globalStore} from "../../../libs/ShareStore";
import {Resource} from "../../../resource/Resource";


export default class WebNavigator implements INavigator {
    root: React.Component<any, NavigatorAppStatesType> | undefined;
    containID: string | undefined;
    pageStacks: Array<NavigatorStack> = new Array<NavigatorStack>();
    config: NavigatorConfig | undefined;
    viewConfigs: any; // {routeKey : viewConfig}

    setRootNavigator(navigator:any){
        // do nothing
    }
    getRootNavigator(){
        // do nothing
    }
    setCurrentNavigator(navigator:any){
        // do nothing
    }
    getCurrentNavigator(){
        // do nothing
    }

    public pop(cb?:()=>void) {
        if (!this.root || !this.containID) {
            Logger.error(`root page or containID not set, please set with initConfig`);
            return;
        }
        let page: NavigatorStack | undefined;
        if (this.pageStacks.length > 0) {
            // page = this.pageStacks.pop()!;
            this.pageStacks.pop();
            if (this.pageStacks.length > 0) {
                page = this.pageStacks[this.pageStacks.length - 1];
            }
        }
        const state = this.root.state;
        state.navigator.root = this.pageStacks.length === 0; // root: false => true
        if (state.navigator.root) {
            this.root.setState(state,()=>{
                if(cb){
                    cb();
                }
            }); // refresh the page
            return; // stack had pop all.
        }
        if (!page) {
            Logger.error(`pop failed, maybe not config ?`);
            return;
        }
        const viewId = page.paramsKey;
        console.log( `viewId:${viewId} `);
        const vconfig = page.viewConfig === undefined ? new NavigatorViewConfig(null) : page.viewConfig;
        // Logger.info(`pop: ready to render page:${page.pageName}`);
        const self = this;
        this.root.setState(state, () => {
            ReactDOM.render(
                <View nativeID={viewId}>
                    {this.renderTitleBar(!vconfig.title ? ' ' : vconfig.title, vconfig)}
                    {page!.componentFunc(page!.paramsKey)}
                </View>,
                document.getElementById(self.containID!),
            );
            if(cb){
                cb();
            }
        });

    }
    public popToRoot() {
        if (!this.root || !this.containID) {
            Logger.error(`root page or containID not set, please set with initConfig`);
            return;
        }
        while (this.pageStacks.length > 0) {
            this.pop();
        }
        return;
    }

    public push: (routeKey: string, paramsKV?:any) => void = (routeKey: string, paramsKV?:any) => {
        const vConfig = this.viewConfigs[routeKey] as NavigatorViewConfig;
        if(vConfig === undefined){
            throw new Error('Could not push, routeKey:' + routeKey + " not found.");
        }

        this._push(vConfig.componentFunc, vConfig, paramsKV)
    }

    public _push(componentFunc: (paramsKey) => React.Component<any, any>, viewConfig?: NavigatorViewConfig, paramsKV?:any) {
        if (!this.root) {
            Logger.error(`root page not exist, please set with initConfig`);
            return;
        }

        const paramsKey = UUID.gen();
        this.pageStacks.push(
            new NavigatorStack(componentFunc, viewConfig, paramsKey),
        );
        if(paramsKV){
            // globalStore.webNavigatorKeyValue[paramsKey] = Beans.to(paramsKV);
            globalStore.webNavigatorKeyValue[paramsKey] = paramsKV;
        }
        const vconfig = viewConfig === undefined ? new NavigatorViewConfig(null) : viewConfig;
        const state = this.root.state;
        state.navigator.root = false; // root: true => false
        const self = this;
        const viewId = paramsKey;
        this.root.setState(state, () => {
            ReactDOM.render(
                <View nativeID={viewId} >
                    {this.renderTitleBar(!vconfig.title ? ' ' : vconfig.title, vconfig)}
                    {componentFunc(paramsKey)}
                </View>,
                document.getElementById(self.containID!),
            );
        });

        return;
    }

    private renderTitleBar(title: string = "", vconfig:NavigatorViewConfig){
        const leftComponent = vconfig.leftBtn ? vconfig.leftBtn : <Image source={Resource.angle} style={NavigatorBarStyle.leftImage} />;
        const rightComponent = vconfig.rightBtn ? vconfig.rightBtn : <View style={NavigatorBarStyle.right}><Text style={NavigatorBarStyle.rightText}>{''}</Text></View>;

        return (
            <View style={NavigatorBarStyle.titleBarContent}>
                <TouchableOpacity activeOpacity={1}
                                  style={NavigatorBarStyle.left}
                                  onPress={() => {
                                    // console.log("left press");
                                    this.pop();
                                  }}>

                    {leftComponent}
                </TouchableOpacity>
                <View style={NavigatorBarStyle.middle}>
                    <Text numberOfLines={1}
                          style={NavigatorBarStyle.middleTitle}>{title}</Text>
                </View>
                {rightComponent}
            </View>
        )
    }


    public initConfig(
        root: React.Component<any, any>,
        containID: string,
        config: NavigatorConfig,
        viewConfigs:any
    ) {
        this.root = root;
        this.containID = containID;
        this.config = config;
        this.viewConfigs = viewConfigs;
    }



}

const NavigatorBarStyle = StyleSheet.create({
    titleBar: {
        // width: width,
        height: 46,
        backgroundColor: '#cc9748',
    },
    titleBarContent: {
        flexDirection: 'row',
        height: 44,
        alignItems: 'center',
        // width: 44,
        justifyContent: 'space-between',
    },
    titleBarSearchContent: {
        flexDirection: 'row',
        height: 32,
        alignItems: 'center',
        width: 32,
    },


    left: {
    },
    leftImage: {
        marginTop:4,
        marginBottom:4,
        marginLeft:20,
        width:8,
        height:16,
    },
    middle: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    middleTitle: {
        fontSize: 18,
        color: "#000",
        alignItems: 'center',
        justifyContent: 'center'
    },
    right: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingRight: 0,
        // marginTop: -12,
    },
    rightText: {
        fontSize: 18,
        color: "#7f7f7f",
        alignItems: 'center',
        justifyContent: 'center'
    },
    rightImage: {
        resizeMode: 'contain',
        marginLeft: 0
    },

    titleLeftImage: {
        marginRight: 0,
        resizeMode: 'contain'
    },

});
